<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="900px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="老人姓名" prop="elderId">
            <el-input
              v-model="formData.elder.name"
              placeholder="请输入老人姓名"
              disabled
              class="mr-1"
            />
            <el-button @click="clickChooseElder">选择老人</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="事故类型" prop="accidentType">
            <el-select
              v-model="formData.accidentType"
              placeholder="请输入事故类型"
              :clearable="true"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ELDER_ACCIDENT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="事故等级" prop="accidentGrade">
            <inputNumber
              v-model="formData.accidentGrade"
              placeholder="请输入事故等级"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发生时间" prop="accidentTime">
            <el-date-picker
              v-model="formData.accidentTime"
              placeholder="请输入发生时间"
              :clearable="true"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="事故原因" prop="accidentReason">
            <el-input
              v-model="formData.accidentReason"
              placeholder="请输入事故原因"
              :clearable="true"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="事故描述" prop="accidentDescribe">
            <el-input
              v-model="formData.accidentDescribe"
              placeholder="请输入事故描述"
              :clearable="true"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="图片" prop="imgUrl">
            <UploadImg v-model="formData.imgUrl" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <ElderCheckInSelect ref="checkInElderSelectRef" @select-value="handleRelatedElder" />
</template>
<script setup name="ElderAccidentEdit" lang="ts">
import * as ElderAccidentApi from '@/api/elder/accident'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as ElderAccidentModel from '@/model/elder/register/ElderAccident'
import ElderCheckInSelect from '@/views/elder/elderCheckIn/ElderCheckInSelect.vue'
import { ElderCheckInStatusEnum } from '@/utils/constants'
const checkInElderSelectRef = ref()
let formType = ''
const { t } = useI18n()
const message = useMessage()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  elderId: '',
  elder: { name: '' },
  accidentType: 1,
  accidentGrade: 0,
  accidentTime: undefined,
  accidentReason: '',
  accidentDescribe: '',
  imgUrl: ''
})
const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  accidentType: [{ required: true, type: 'number', message: '请输入事故类型', trigger: 'change' }],
  accidentTime: [{ required: true, type: 'date', message: '请输入发生时间', trigger: 'change' }]
})
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ElderAccidentApi.get(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    elderId: '',
    elder: { name: '' },
    accidentType: 1,
    accidentGrade: 0,
    accidentTime: undefined,
    accidentReason: '',
    accidentDescribe: '',
    imgUrl: ''
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ElderAccidentModel.ElderAccident
    if (formType === 'create') {
      await ElderAccidentApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await ElderAccidentApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const clickChooseElder = () => {
  checkInElderSelectRef.value.open({ status: { value: ElderCheckInStatusEnum.CHECKED_IN } })
}

const handleRelatedElder = async (row) => {
  formData.value.elderId = row.elderId
  formData.value.elder.name = row.elder.name
}
</script>
